<template>
  <el-row>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ name: 'dashboard' }">控制台</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ name: 'act' }">优惠活动</el-breadcrumb-item>
      <el-breadcrumb-item>新建优惠活动</el-breadcrumb-item>
    </el-breadcrumb>

    <blank />

    <el-form v-loading="dataLoading" :model="act" ref="act" label-width="100px" class="" @keyup.enter.native="submitForm('act')">

      <el-form-item label="链接图片">
        <el-upload
          class="upload"
          :action="fileServer"
          :on-success="uploadLinkOK"
          :before-upload="clearLink"
          :show-file-list="false">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>

        <div v-if="linkSrc">
          <img :src="linkSrc" />
        </div>

      </el-form-item>      

      <el-form-item label="详情图片">
        <el-upload
          class="upload"
          :action="fileServer"
          :on-success="uploadDetailOK"
          :before-upload="clearDetail"
          :show-file-list="false">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>

        <div v-if="detailSrc">
          <img :src="detailSrc" />
        </div>
      </el-form-item>

      <el-form-item label="活动过期时间" prop="ActivityExpired" :rules="[{ required: true, message: '活动过期时间不能为空'}]">
        <el-date-picker
          v-model="act.ActivityExpired"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions0">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="是否开启活动">
        <el-switch
          v-model="act.IsShow"
          on-color="#13ce66"
          off-color="#ff4949">
        </el-switch>
      </el-form-item>

      <el-form-item label="优惠券标题" prop="Title" :rules="[
        { required: true, message: '标题不能为空'},
        { min: 1, max: 20, message: '长度在 1 到 20 个字符' }]">
        <el-input v-model="act.Title"></el-input>
      </el-form-item>

      <el-form-item label="优惠券说明" prop="Detail" :rules="[
        { required: true, message: '说明不能为空'},
        { min: 1, max: 300, message: '长度在 1 到 300 个字符' }]">
        <el-input v-model="act.Detail"></el-input>
      </el-form-item>

      <el-form-item label="优惠券价值" prop="Worth" :rules="[
        { required: true, message: '价值不能为空'},
        { type: 'number', message: '价值必须为数字值'} ]">
        <el-input v-model.number="act.Worth"></el-input>
      </el-form-item>
      
      <el-form-item label="优惠券过期时间" prop="Expired" :rules="[{ required: true, message: '过期时间不能为空'}]">
        <el-date-picker
          v-model="act.Expired"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions0">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="使用场景">
        <el-checkbox-group v-model="sceneList" v-loading="loading">
          <div class="scene-tip">若不选，默认为无限制使用；选择之后，只能在对应的下单场景使用</div>
          <div v-for="(group, key, index) in targets" :key="group.key">
            <el-tag :type="key | lable">{{ group.desc }}</el-tag>
            <el-checkbox v-for="(target, key, index) in group.data" :key="target.Id" :label="target.Code" :disabled="target.Item | sceneDisabled">{{ target.Target  | scene(target.Item) }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item>
        <el-button :loading="loadingState" type="primary" @click="submitForm('act')">保存</el-button>
        <el-button @click="resetForm('act')">重置</el-button>
      </el-form-item>
    </el-form>    

  </el-row>
</template>

<script>
  import blank from '@/components/Blank'
  import { Message } from 'element-ui'
  import ax, { errhandler, domain } from '@/api/_axios-config'
  import * as apis from '@/api/_api'
  import router from '@/router'

  export default {
    name: 'addact',
    filters: {
      scene: function (target, item) {
        if (item === 1) {
          return '开荒保洁'
        } else if (item === 3) {
          return '地毯清洗'
        } else if (item === 2) {
          return '玻璃清洗'
        } else if (item === 7) {
          return '定制服务'
        } else {
          return target
        }
      },
      sceneDisabled: function (item) {
        if (item === 1 || item === 2 || item === 3 || item === 7) {
          return true
        } else {
          return false
        }
      },
      lable: function (key) {
        if (key % 2 === 0) {
          return ''
        } else {
          return 'primary'
        }
      }
    },
    data () {
      return {
        linkSrc: null,
        detailSrc: null,
        fileServer: domain + apis.FILE_UPLOAD,
        callDialog: false,
        domain: domain,
        targets: [],
        sceneList: [],
        loading: true,
        loadingState: false,
        dataLoading: true,
        pickerOptions0: {
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        act: {
          DetailImgUrl: '',
          LinkImgUrl: '',
          ActivityExpired: '',
          IsShow: '',
          Title: '',
          Worth: 0,
          Expired: '',
          Detail: '',
          Scene: ''
        }
      }
    },
    methods: {
      uploadLinkOK (response, file, fileList) {
        var path = domain + response
        this.linkSrc = path
      },
      uploadDetailOK (response, file, fileList) {
        var path = domain + response
        this.detailSrc = path
      },
      clearLink (file) {
        this.linkSrc = ''
      },
      clearDetail (file) {
        this.detailSrc = ''
      },
      getTarget () {
        ax.get(apis.ALL_TARGET).then(response => {
          let result = response.data
          if (result.BoolStatus) {
            let targets = result.Data
            let data = []
            let temp = null
            let group = []
            let count = 0
            for (let i = 0; i < targets.length; i++) {
              if (temp == null) {
                temp = targets[i]
                group.push(targets[i])
              } else {
                if (temp.Item === targets[i].Item) {
                  temp = targets[i]
                  group.push(targets[i])
                } else {
                  let desc = ''
                  switch (temp.Item) {
                    case 0:
                      desc = '日常保洁'
                      break
                    case 1:
                      desc = '开荒保洁'
                      break
                    case 2:
                      desc = '玻璃清洗'
                      break
                    case 3:
                      desc = '地毯清洗'
                      break
                    case 4:
                      desc = '空调清洗'
                      break
                    case 5:
                      desc = '油烟机清洗'
                      break
                    case 6:
                      desc = '包月服务'
                      break
                    case 7:
                      desc = '定制服务'
                      break
                  }
                  data.push({key: count, desc: desc, data: group})
                  group = [targets[i]]
                  count++
                  temp = targets[i]
                }
              }
            }
            this.targets = data
          } else {
            Message.error(result.Message)
          }
          this.loading = false
        }).catch(err => {
          errhandler(err)
          this.loading = false
        })
      },
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loadingState = true

            if (this.linkSrc === null || this.linkSrc === '') {
              Message.error('活动链接图片未选择')
            }

            if (this.detailSrc === null || this.detailSrc === '') {
              Message.error('活动详情图片未选择')
            }

            this.act.LinkImgUrl = this.linkSrc
            this.act.DetailImgUrl = this.detailSrc

            if (this.sceneList !== null && this.sceneList.length > 0) {
              this.act.Scene = ''
              for (let i = 0; i < this.sceneList.length; i++) {
                this.act.Scene += this.sceneList[i] + ','
              }
              this.act.Scene = this.act.Scene.substring(0, this.act.Scene.length - 1)
            }

            ax.post(apis.ADD_OR_UPDATE_ACT, this.act).then(response => {
              let result = response.data
              if (result.BoolStatus) {
                this.$alert('保存活动成功', '结果', {
                  confirmButtonText: '确定',
                  callback: action => {
                    router.go(0)
                  }
                })
              } else {
                Message.error(result.Message)
                this.loadingState = false
              }
            }).catch(err => {
              this.loadingState = false
              errhandler(err)
            })
          } else {
            return false
          }
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      }
    },
    components: { blank },
    created: function () {
      let params = this.$route.params
      if (params.actId === undefined) {
        this.dataLoading = false
      } else {
        ax.get(apis.ACT_DETAIL, { params: { id: params.actId } }).then(response => {
          let result = response.data
          if (result.BoolStatus) {
            this.act = {}
            this.act = {
              Id: result.Data['Id'],
              DetailImgUrl: result.Data['DetailImgUrl'],
              LinkImgUrl: result.Data['LinkImgUrl'],
              ActivityExpired: result.Data['ActExpiredString'],
              IsShow: result.Data['IsShow'],
              Title: result.Data['Title'],
              Worth: result.Data['Worth'],
              Expired: result.Data['ExpiredString'],
              Detail: result.Data['Detail'],
              Scene: result.Data['Scene']
            }
            this.linkSrc = this.act.LinkImgUrl
            this.detailSrc = this.act.DetailImgUrl
            if (this.act.Scene !== '' && this.act.Scene !== null) {
              let group = this.act.Scene.split(',')
              for (let i = 0; i < group.length; i++) {
                this.sceneList.push(group[i])
              }
            }
          }
          this.dataLoading = false
        }).catch(err => {
          errhandler(err)
        })
      }
      this.getTarget()
    }
  }
</script>

<style lang="stylus">

.el-dropdown-link
  cursor pointer
  color #20a0ff

.upload-container
  width 360px

.scene-tip
  color #d6292e
  font-weight bold

div.preview-container
    width 100%
    img.preview-img
      display block
      max-width 100%
      margin auto
      border 1px solid gray
</style>
